<template>
	<div class="container">
		<h2>{{ cId ? '修改' : '创建' }}主要物资子合同</h2>
		<a-form ref="formRef" :model="formState" layout="vertical" :disabled="true" @finish="saveContract">
			<a-row :gutter="20">
				<a-col :span="6">
					<a-form-item label="原合同名称" name="parent_name" :rules="{ required: true }">
						{{ formState.parent_name }}
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="合同编号" name="parent_code" :rules="{ required: true }">
						{{ formState.parent_code }}
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="项目名称" name="project_name" :rules="{ required: true }">
						{{ formState.project_name }}
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="计划名称" name="plan_name" :rules="{ required: true }">
						{{ formState.plan_name }}
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="供应商名称" name="plan_name" :rules="{ required: true }">
						{{ formState.supplier_name }}
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="合同类型" name="price_type" :rules="{ required: true }">
						{{ formState.price_type === 1 ? '固定单价合同' : (formState.price_type === 2 ? '单价*浮动率合同': '单价*浮动价合同') }}
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="专项类型" name="material_type" :rules="{ required: true }">
						{{ formState.material_type === 1 ? '其他' : (formState.price_type === 2 ? '混凝土专项': '钢筋专项') }}
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="客户联系人" name="contact" :rules="{ required: true, message: '请输入客户联系人' }">
						<a-input v-model:value="formState.contact" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="签订时间" name="sign_time" :rules="{ required: true, message: '请输入签订时间' }">
						<a-date-picker v-model:value="formState.sign_time" value-format="YYYY-MM-DD" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="合同" name="file_path" :rules="{ required: true, message: '请上传合同附件' }">
						<a-upload v-model:file-list="formState.file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeUpload" @change="changeUpload">
							<a-button>
								<template v-if="uploading">
									<loading-outlined />上传中...
								</template>
								<template v-else>
									<import-outlined />上传合同附件
								</template>
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="采购方式" name="purchase_way_id" :rules="{ required: true, message: '请选择采购方式' }">
						<a-select v-model:value="formState.purchase_way_id" :show-search="true" placeholder="请选择采购方式" :options="purchaseWays" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="付款方式" name="pay_way_id" :rules="{ required: true, message: '请选择付款方式' }">
						<a-select v-model:value="formState.pay_way_id" :show-search="true" placeholder="请选择付款方式" :options="payWays" option-filter-prop="label"></a-select>
					</a-form-item>
				</a-col>
				<template v-if="formState.material_type === 2">
					<a-col v-if="!formState.art_indexes?.length" :span="6">
						<a-form-item label="技术指标" name="art_indexes">
							<a-button type="primary" ghost @click="addArtIndex">+</a-button>
						</a-form-item>
					</a-col>
					<a-col v-for="(item, i) in formState.art_indexes" v-else :key="i" :span="6">
						<a-form-item label="技术指标" name="art_indexes">
							<a-input-group compact class="">
								<a-select v-model:value="item.gonghao_id" :options="artIndexesGongHaos" style="width: 150px;" placeholder="请选择技术指标" allow-clear @change="changeArtIndex(item)"></a-select>
								<a-input-number v-model:value="item.price" style="width:30%" placeholder="请输入价格" allow-clear />
								<a-button type="primary" danger ghost @click="delArtIndex(i)">-</a-button>
								<a-button v-if="i + 1 === formState.art_indexes.length" type="primary" ghost @click="addArtIndex">+</a-button>
							</a-input-group>
						</a-form-item>
					</a-col>
				</template>
				<a-col :span="24">
					<h1 style="font-size:18px;text-align: center;font-weight:bold">合同物资清单</h1>
					<div class="table-toolbar mb-3">
						<a-space>
							<a-button type="primary" @click="addMaterialModel">
								<plus-outlined />新增
							</a-button>
							<!--
              <a-button class="cache-btn" @click="handleCache">
                <DeliveredProcedureOutlined />暂存
              </a-button>
              -->
							<a-button @click="fillInBatch">
								<BarsOutlined />批量填充
							</a-button>
						</a-space>
					</div>
					<a-table :scroll="tableScroll" :pagination="pagination" :data-source="formState.materials" :columns="columns" :row-key="(record) => record.key" @change="handleTableChange">
						<template #bodyCell="{ column, record, index, text }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', record.key, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
									<a-tree-select v-model:value="record.source_id" :class="check(record.id,column.columnKey,text) ? 'change-red' : ''" :show-search="true" placeholder="请选择材料名称" allow-clear :tree-data="materialOptions" tree-node-filter-prop="label" :disabled="!!record.parent_material_id" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', record.key, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="record.id" :class="check(record.id,column.columnKey,text) ? 'change-red' : ''" :show-search="true" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'id', label: 'model' }" :disabled="!!record.parent_material_id" style="width:100%" @change="(id) => changeModel(id, record, materialModelOptions[record.source_id])"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'intro'">
								<a-form-item :name="['materials', record.key, 'intro']" :class="check(record.id,column.columnKey,text) ? 'change-red' : ''">
									<a-input v-model:value="formState.materials[index].intro" placeholder="请输入详细规格" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', record.key, 'unit']">
									{{ record.unit || '-' }}
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'up_per' && Number(formState.price_type) === 2">
								<a-form-item :name="['materials', record.key, 'up_per']" :rules="{ required: true, message: '请输入浮动率' }" :class="check(record.id,column.columnKey,text) ? 'change-red' : ''">
									<a-input-number v-model:value="record.up_per" placeholder="浮动率" suffix="%" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'up_per' && Number(formState.price_type) === 3">
								<a-form-item :name="['materials', record.key, 'up_per']" :rules="{ required: true, message: '请输入浮动价格' }">
									<a-input-number v-model:value="record.up_per" placeholder="浮动价格" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'without_tax_subprice_base'">
								<a-form-item :name="['materials', record.key, 'without_tax_subprice_base']" :class="check(record.id,column.columnKey,text) ? 'change-red' : ''" :rules="{ required: true, message: '请输入不含税基准价格' }">
									<a-input-number v-model:value="record.without_tax_subprice_base" placeholder="请输入不含税基准价格" :min="0" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'diff_quantity'">
								<a-form-item :name="['materials', record.key, 'diff_quantity']" :rules="{ required: true, message: '请输入修正数量' }">
									<a-input-number v-model:value="record.diff_quantity" placeholder="请输修正入数量" @blur="resultQuantity(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'tax'">
								<a-form-item :name="['materials', record.key, 'tax']" :rules="{ required: true, message: '请输入税率' }" :class="check(record.id,column.columnKey,text) ? 'change-red' : ''">
									<a-input-number v-model:value="record.tax" placeholder="税率" suffix="%" :min="0" @blur="authPriceCalculation(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', record.key, 'memo']">
									<a-input v-model:value="record.memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-popconfirm v-if="Number(record.completed_quantity) === 0 || !record.parent_material_id" title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<template v-if="!record.parent_material_id">
											<a-button type="link" style="color:#ff7875">
												<delete-outlined />删除
											</a-button>
										</template>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
						<template #summary>
							<a-table-summary-row style="background-color:#f0f0f0;font-size:12px;font-weight:bold;">
								<a-table-summary-cell :col-span="2">
									<a-typography-text>合计</a-typography-text>
								</a-table-summary-cell>

								<a-table-summary-cell v-if="Number(formState.price_type) === 1" :col-span="10"></a-table-summary-cell>
								<a-table-summary-cell v-else :col-span="12"></a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ formState.amount }}</a-typography-text>
								</a-table-summary-cell>

								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ formState.with_tax_amount }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ formState.tax_amount }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
							</a-table-summary-row>
						</template>
					</a-table>
				</a-col>
			</a-row>
			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button v-if="!formState.id || ![0, 1, 2].includes(formState.workflow_status)" v-permission="271" type="primary" html-type="submit" :loading="loading">
							<save-outlined />保存
						</a-button>
						
						<a-workflow v-if="formState.id" v-model:status="formState.workflow_status" module="contractChild" :target-id="formState.id" :project-id="formState.project_id" :code="formState.code" :user-id="formState.opr_id" @submit="submitPurchase"></a-workflow>
						<a-button @click="closeTab('/contract')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
		<a-modal v-model:visible="visible" :width="400" title="批量填充" @ok="fillIn">
			<a-form ref="formFillRef" :model="fillInData">
				<a-row>
					<a-col :span="24">
						<a-form-item label="填充字段" name="column_key" :rules="{ required: true, message: '请选择填充字段' }">
							<a-select v-model:value="fillInData.column_key" :show-search="true" placeholder="请选择填充字段" :options="innerFillColumnOptions" option-filter-prop="label"></a-select>
						</a-form-item>
					</a-col>
					<a-col v-if="fillInData.column_key === 'plan_material'" :span="24">
						<a-form-item label="选择子计划" name="id" :rules="{ required: true, message: '请选择子计划物料单' }">
							<a-select v-model:value="fillInData.id" :show-search="true" placeholder="请选择子计划物料单" :options="planOptions" option-filter-prop="label"></a-select>
						</a-form-item>
					</a-col>
					<a-col v-else :span="24">
						<a-form-item label="填充内容" name="column_val" :rules="{ required: true, message: '请输入填充内容' }">
							<a-input v-model:value="fillInData.column_val" placeholder="请输入填充内容" />
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-modal>
	</div>
</template>
<script setup>
import { useRoute, useRouter } from "vue-router";
import { computed, getCurrentInstance, inject, onMounted, ref, render, watch } from "vue";
import { post, postJson } from "@/utils/index.js";
import _ from "lodash-es";
import { baseURL } from "@/utils/request.js";
import {
	BarsOutlined,
	CloseOutlined,
	DeleteOutlined,
	ImportOutlined,
	LoadingOutlined,
	PlusOutlined, SaveOutlined
} from "@ant-design/icons-vue";
import { add, subtract } from "@/utils/operation.js";
import { AWorkflow } from "@/components/index.js";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const formState = ref({ materials: [] });
const parentInfo = ref({});
const formRef = ref();
const id = computed(() => {
	return route.params.id || 0;
});
const cId = computed(() => {
	return route.params.cid || 0;
});
const uploading = ref(false);
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 680 }));
const columns = computed(() => {
	let _columns = [
		{
			title: "ID",
			dataIndex: "key",
			width: 60,
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text + 1;
			}
		},
		{
			title: "物资名称",
			dataIndex: "name",
			width: 250,
			columnKey: "name",
			ellipsis: true,
			align: "center",
		},
		{
			title: "型号规格",
			dataIndex: "model",
			width: 150,
			columnKey: "model",
			ellipsis: true,
			align: "center"
		},
		{
			title: "详细规格",
			dataIndex: "intro",
			width: 150,
			columnKey: "ContractMaterial.intro",
			ellipsis: true,
			align: "center"
		},
		{
			title: "单位",
			dataIndex: "unit",
			width: 120,
			align: "center"
		},
		// 原合同数量quantity-已验收数量completed_quantity = 原合同余量
		{
			title: "原合同数量",
			dataIndex: "parent_quantity",
			width: 100,
			align: "center",
		},
		{
			title: "原合同已验收数量",
			dataIndex: "parent_completed_quantity",
			width: 120,
			align: "center",
		},
		{
			title: "原合同余量",
			dataIndex: "parent_pending_quantity",
			width: 100,
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return record.parent_quantity - record.parent_completed_quantity || 0;
			}
		},
		{
			title: "修正数量", 
			dataIndex: "diff_quantity",
			width: 100,
			align: "center",
		},
		{
			title: "修正后合同数量",
			dataIndex: "quantity",
			width: 110,
			align: "center",
		},
		// {
		// 	title: "已验收数量",
		// 	dataIndex: "completed_quantity",
		// 	width: 100,
		// 	align: "center"
		// },
		{
			title: formState.value.price_type === 1 ? "不含税单价(元)" : "不含税基准价格(元)",
			dataIndex: "without_tax_subprice_base",
			width: 150,
			columnKey: "ContractMaterial.without_tax_subprice_base",
			align: "center"
		},
		{
			title: "税率%",
			dataIndex: "tax",
			width: 120,
			columnKey: "ContractMaterial.tax",
			align: "center"
		},
	]
	if (Number(formState.value.price_type) === 2) {
		_columns.push({
			title: "浮动比率±(%)",
			dataIndex: "up_per",
			width: 120,
			columnKey: "ContractMaterial.up_per",
			align: "center"
		})
	} else if (Number(formState.value.price_type) === 3) {
		_columns.push({
			title: "浮动价格(±)",
			dataIndex: "up_per",
			width: 120,
			align: "center"
		},)
	}
	_columns = [
		..._columns,
		...(formState.value.price_type !== 1 ? [{
			title: "不含税单价(元)",
			dataIndex: "without_tax_subprice",
			width: 120,
			align: "center"
		}] : []),
		{
			title: "不含税总价(元)",
			dataIndex: "without_tax_amount",
			width: 120,
			align: "center"
		},
		{
			title: "含税单价(元)",
			dataIndex: "with_tax_subprice",
			width: 120,
			align: "center"
		},
		{
			title: "含税总价",
			dataIndex: "with_tax_amount",
			width: 120,
			align: "center"
		},
		{
			title: "税额",
			dataIndex: "tax_amount",
			width: 120,
			align: "center"
		},
		{
			title: "操作",
			key: "operation",
			sorter: false,
			fixed: "right",
			width: 200,
			align: "center"
		}
	]
	return _columns;
})
const fillColumnOptions = [
	{
		label: "税率%",
		value: "tax"
	},
	{
		label: "浮动价格(±)",
		value: "up_per"
	},
	{
		label: "浮动比率±(%)",
		value: "up_per"
	},
	{
		label: "子计划物料",
		value: "plan_material"
	}
];
const pagination = ref({
	current: 1,
	pageSize: 50,
});
const handleTableChange = (pag, filters, sorter) => {
	Object.assign(pagination.value,
		{
			current: pag.current,
			pageSize: 50,
		}
	)
}
const toLastPage = () => {
	const total = formState.value.materials.length;
	const lastPage = Math.ceil(total / pagination.value.pageSize);
	Object.assign(pagination.value,
		{
			current: lastPage,
			pageSize: 50,
			total: total,
		}
	)
}
const innerFillColumnOptions = computed(() => {
	let options = [];
	switch (parseInt(formState.value.price_type)) {
	case 3:
		options = fillColumnOptions.filter(column => column.label !== "浮动比率±(%)");
		break;
	case 2:
		options = fillColumnOptions.filter(column => column.label !== "浮动价格(±)");
		break;
	case 1:
		options = fillColumnOptions.filter(column => column.value !== "up_per");
		break;
	}
	return options;
});
onMounted(async () => {
	const parentContractInfo = await post("contract/info", { id: id.value });
	parentInfo.value = parentContractInfo;

	const contractInfo = cId.value ? (await post("contract/info", { id: cId.value })) : parentContractInfo;
	if (cId.value && contractInfo.parent_id !== Number(id.value)) {
		proxy.$message.error("合同数据异常");
		setTimeout(() => {
			closeTab('/contract');
		}, 500)
		return;
	}
	let amount = 0;
	let wt_amount = 0;
	let t_amount = 0;
	formState.value = {
		parent_id: id.value,
		parent_name: parentContractInfo.name,
		parent_code: parentContractInfo.code,
		project_name: contractInfo.project?.name,
		plan_name: contractInfo.plan?.name,
		supplier_name: contractInfo.supplier?.company_name,
		..._.pick(contractInfo, [
			"project_id", "plan_id", "supplier_id", "price_type", "material_type", "contact", "sign_time",
			"purchase_way_id", "pay_way_id", "code"
		]),
		name: parentContractInfo.name,
		file_path: contractInfo.file_path ? JSON.parse(contractInfo.file_path) : [],
		art_indexes: contractInfo.art_indexes ? JSON.parse(contractInfo.art_indexes) : [],
		opr_id: contractInfo.opr_id,
	};
	if (cId.value) {
		formState.value.id = cId.value;
	}
	formState.value.materials = contractInfo.materials.map((d, i) => {
		const parentMaterial = parentContractInfo.materials.find(item => item.id === d.id);
		d.key = i;
		const { intro, unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, with_tax_subprice, with_tax_amount, tax_amount, tax, standard, add_time, use_time, time_unit, useto, memo, pending_quantity, completed_quantity } = d.ContractMaterial;
		d.intro = intro;
		d.unit = unit;
		d.quantity = quantity;
		d.without_tax_subprice_base = without_tax_subprice_base;
		d.parent_material_id = parentMaterial?.id;
		d.down_per = down_per;
		d.up_per = up_per;
		d.without_tax_subprice = without_tax_subprice;
		d.without_tax_amount = without_tax_amount;
		d.tax = tax;
		d.with_tax_subprice = with_tax_subprice;
		d.with_tax_amount = with_tax_amount;
		d.tax_amount = tax_amount;

		d.standard = standard;
		d.add_time = add_time;
		d.use_time = use_time;
		d.time_unit = time_unit;
		d.useto = useto;
		d.memo = memo;
		d.pending_quantity = pending_quantity;
		d.completed_quantity = parentMaterial ? parentMaterial.ContractMaterial.completed_quantity : completed_quantity;
		// 原合同数量
		d.parent_quantity = parentMaterial?.ContractMaterial.quantity || 0
		// 原合同已验收数量
		d.parent_completed_quantity = parentMaterial?.ContractMaterial.completed_quantity || 0
		// 编辑页面修正数量取值
		d.diff_quantity = subtract([quantity, d.parent_quantity], 3)
		wt_amount = parseFloat(wt_amount) + parseFloat(with_tax_amount);
		amount = parseFloat(amount) + parseFloat(without_tax_amount);
		t_amount = parseFloat(t_amount) + parseFloat(tax_amount);
		return d;
	})
	
	formState.value.amount = parseFloat(amount).toFixed(2);
	formState.value.with_tax_amount = wt_amount.toFixed(2);
	formState.value.tax_amount = t_amount.toFixed(2);
	post("dictionary", { plan_id: formState.value.plan_id, workflow_status: 2 }).then(data => {
		//	const { root_id: rootId } = data[0] || {};
		materialOptions.value = data;
		//获取所有规格
		post("material", { source_id: data.map(d => d.id).join(","), plan_id: formState.value.plan_id, page_size: Infinity, workflow_status: 2 }).then(({ data }) => {
			materialModelOptions.value = (() => {
				const array = [];
				data.forEach(d => {
					if (!array[d.source_id]) array[d.source_id] = [];

					if (d.attr) d.model = `${d.model}（${d.attr}）`;

					array[d.source_id].push(d);
				});

				return array;
			})(data);
		});
	});
	// 默认进来计划名称有值
	if (formState.value.plan_id) {
		planList()
	}
	pagination.value["total"] = formState.value.materials.length
})
const planOptions = ref([])
// 查询子计划列表数据
const planList = () => {
	post("plan", { type: 1, parent_id: formState.value.plan_id, workflow_status: 2 }).then(res => {
		const { data } = res
		data.forEach(item => {
			planOptions.value.push({ value: item.id, label: item.name })
		})
	})
}
import lodash from 'lodash-es'
// 对比数据 发生变化更改字体样式为红色
function check(materialId, checkColumnName, text, index) {
	const result = parentInfo.value.materials.find((i) => i.id === materialId)
	return lodash.get(result, checkColumnName) !== text;
}
const beforeUpload = file => {
	return new Promise(resolve => {
		uploading.value = true;
		if (file.type !== "application/pdf") {
			proxy.$message.error("只能上传PDF文件");
			uploading.value = false;
			return false;
		}

		const isLt10M = file.size / 1024 / 1024 < 20;
		if (!isLt10M) {
			proxy.$message.error("只能上传10MB以下文件");
			uploading.value = false;
			return false;
		}

		resolve(true);
	});
};
// 上传并提交文件
const changeUpload = ({ file }) => {
	if (file.status === "done") {
		formState.value.file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
		uploading.value = false;
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		formState.value.file_path = formState.value.file_path.filter((item) => item.url);
	}
};
const purchaseWays = ref([]);
post("dictionary", { root_id: 1501 }).then((data) => {
	purchaseWays.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const payWays = ref([]);
post("dictionary", { root_id: 1506 }).then((data) => {
	payWays.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});

const artIndexesGongHaos = ref([]);
post("dictionary", { root_id: 1069 }).then((data) => {
	artIndexesGongHaos.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
watch(() => formState.value.materials.length, (len) => {
	pagination.value.total = len;
})
const addArtIndex = () => {
	if (!formState.value.art_indexes) {
		formState.value.art_indexes = [];
	}
	formState.value.art_indexes.push({
		gonghao_id: null,
		price: null,
	})
}
const delArtIndex = (i) => {
	formState.value.art_indexes.splice(i, 1);
}

const changeArtIndex = (record) => {
	const gonghaoIdMap = {};
	for (const item of formState.value.art_indexes) {
		if (!item.gonghao_id) continue;
		if (gonghaoIdMap[item.gonghao_id] > 0) {
			record.gonghao_id = null;
			proxy.$message.error("请勿选择相同的技术指标");
			break;
		} else
			gonghaoIdMap[item.gonghao_id] = 1;
	}
}
const addMaterialModel = () => {
	if (!formState.value.purchase_way_id || !formState.value.pay_way_id || !formState.value.code || !formState.value.plan_id || !formState.value.supplier_id || !formState.value.price_type || !formState.value.material_type || !formState.value.contact || !formState.value.file_path) {
		proxy.$message.error("请将基本信息填写完善再录入物资清单");
		return;
	}
	formState.value.materials.push({ key: formState.value.materials.length });
	toLastPage()
};
const fillInData = ref({});
const visible = ref(false);
const formFillRef = ref();
const fillInBatch = () => {
	fillInData.value = {};
	visible.value = true;
};
const fillIn = () => {
	formFillRef.value.validate().then(() => {
		if (fillInData.value.column_key !== 'plan_material') {
			proxy.$message.destroy();
			formState.value.materials.map(item => {
				item[fillInData.value["column_key"]] = fillInData.value["column_val"];
				authPriceCalculation(item);
			});
			proxy.$message.success("填充成功", 1);
		} else {
			// 请求子计划物料列表接口 渲染物料列表数据 对比有没有重复
			post("plan/info", { id: fillInData.value["id"] }).then(data => {
				const { materials } = data;
				const materialIds = formState.value.materials.map(item => item.id);
				for (const material of materials) {
					if (materialIds.includes(material.id)) continue;
					formState.value.materials.push({
						id: material.id,
						source_id: material.source_id,
						unit: material.unit,
						key: formState.value.materials.length,
					})
				}
				toLastPage()
			})
		}
		visible.value = false;
	});
};
const authPriceCalculation = (record) => {
	if (!(record.without_tax_subprice_base > 0)) return;
	if (!record.quantity) return;
	if (!(Number(record.tax) >= 0)) return;
	const priceType = parseInt(formState.value.price_type);
	// if (priceType !== 1 && typeof Number(record.up_per) !== 'number') return;
	if (priceType === 1) {
		record.without_tax_subprice = record.without_tax_subprice_base;
		record.with_tax_subprice = record.without_tax_subprice * 100 * ((1 + record.tax / 100) * 1000) / 100000;
	} else if (priceType === 2) {
		record.without_tax_subprice = record.without_tax_subprice_base * 100 * ((1 + (typeof Number(record.up_per) !== 'number' ? 0 : record.up_per) / 100) * 1000) / 100000;
		record.with_tax_subprice = record.without_tax_subprice * 100 * ((1 + record.tax / 100) * 1000) / 100000;
	} else if (priceType === 3) {
		record.without_tax_subprice = add([record.without_tax_subprice_base, record.up_per], 2);
		record.with_tax_subprice = record.without_tax_subprice * 100 * ((1 + record.tax / 100) * 1000) / 100000;
	}
	record.without_tax_amount = record.without_tax_subprice * 100 * (record.quantity * 100) / 10000;
	record.with_tax_amount = record.with_tax_subprice * 100 * (record.quantity * 100) / 10000;
	record.tax_amount = subtract([record.with_tax_amount, record.without_tax_amount], 2);
	calAmount();
}
const calAmount = () => {
	let amount = 0;
	let with_tax_amount = 0;
	let tax_amount = 0;

	formState.value.materials.map(d => {
		const formatColumn = ["with_tax_subprice", "with_tax_amount", "without_tax_subprice", "without_tax_amount", "quantity"];
		for (const key of formatColumn) {
			if (!d[key] || parseFloat(d[key]) === 0 || d[key] < 0) {
				d[key] = null;
			} else {
				d[key] = parseFloat(d[key] || 0).toFixed(2);
			}
		}
		if (d.with_tax_subprice && d.without_tax_subprice && parseFloat(d.with_tax_subprice) < parseFloat(d.without_tax_subprice)) {
			proxy.$message.error("含税单价不能小于不含税单价");
			d.with_tax_subprice = null;
		}

		if (d.with_tax_amount && d.without_tax_amount && parseFloat(d.with_tax_amount) < parseFloat(d.without_tax_amount)) {
			proxy.$message.error("含税总价不能小于不含税总价");
			d.with_tax_amount = null;
		}
		// d.up_per = parseFloat(d.up_per || 0).toFixed(2);
		// d.down_per = parseFloat(d.down_per || 0).toFixed(2);
		// d.tax = parseFloat(d.tax || 0).toFixed(2);
		//
		// d.tax_amount = parseFloat(d.tax_amount || 0).toFixed(2);
		if (d.with_tax_amount && d.without_tax_amount) {
			d.tax_amount = subtract([d.with_tax_amount, d.without_tax_amount]);
		}
		amount += parseFloat(d.without_tax_amount || 0);
		with_tax_amount += parseFloat(d.with_tax_amount || 0);
		tax_amount += parseFloat(d.tax_amount || 0);
	});

	formState.value.amount = parseFloat(amount).toFixed(2);
	formState.value.with_tax_amount = parseFloat(with_tax_amount).toFixed(2);
	formState.value.tax_amount = parseFloat(tax_amount).toFixed(2);
};
const materialOptions = ref([]);
const materialModelOptions = ref({});
const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;
	if (!id) return;
	post("material", { source_id: id, plan_id: formState.value.plan_id, page_size: Infinity, workflow_status: 2 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;
			return d;
		});
	});
};
const changeModel = (id, record, options) => {
	const { unit = "" } = options.find(d => d.id === id);
	if (formState.value.materials.filter(d => d.id === id).length > 1) {
		record.id = null;
		return proxy.$message.error("该物料规格已存在合同列表，请选择其他规格或物料");
	}
	formState.value.materials.find(d => d.key === record.key).unit = unit;
};
// 计算修正后数量
const resultQuantity = async record => {
	record.quantity = add([record.parent_quantity, record.diff_quantity], 3)
	await checkqty(record)
}
// 计算总金额
const checkqty = async record => {
	if (record.id > 0) {
		if (record.quantity < record.completed_quantity) {
			record.quantity = record.completed_quantity;
		}
		if (!record.quantity) {
			record.quantity = null;
			return;
		}
		//当前的物资数量
		let current_qty = 0;
		formState.value.materials.map(d => {
			if (d.id === record.id) {
				current_qty = current_qty + parseFloat(d.quantity);
			}
		});
		const contractHistory = await post("contract/all", { plan_id: formState.value.plan_id });
		const history_current_qty = contractHistory.reduce((target, item) => {
			if (parseInt(item.id) === parseInt(route.params.id)) return target;
			for (const material of item.materials) {
				if (material.id !== record.id) {
					continue;
				}
				target = target + parseFloat(material.ContractMaterial.quantity);
			}
			return target;
		}, 0);
		post("contract/plan_num", { plan_id: formState.value.plan_id, material_id: record.id }).then(num => {
			if (current_qty > num - history_current_qty) {
				proxy.$message.error("合同清单数量不能超过计划数量");
				let now_qty = parseFloat(num) - parseFloat(history_current_qty) - parseFloat(current_qty) + parseFloat(record.quantity);
				if (now_qty < 0) {
					now_qty = 0;
				}
				formState.value.materials[record.key]["quantity"] = now_qty;
			}

			authPriceCalculation(record);
		});
	}
};
const deleteMaterialModel = key => {
	const { materials } = formState.value;

	const index = materials.findIndex(d => d.key === key);
	if (index === false) return;
	materials.splice(index, 1);

	formState.value = {
		...formState.value,
		materials: materials.map((d, i) => {
			d.key = i;
			return d;
		})
	};
	calAmount();
};
const loading = ref(false)
const saveContract = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			for (const artIndex of formState.value.art_indexes) {
				// if (!!artIndex.gonghao_id ^ !!artIndex.price) {
				// 	proxy.$message.error("请完善技术指标");
				// 	return;
				// }
				if (artIndex.gonghao_id && !(parseFloat(artIndex.price) >= 0)) {
					proxy.$message.error("请完善技术指标");
					return;
				}
			}
			const { id, name, type, price_type, material_type, code, contact, file_path, project_id, plan_id, supplier_id, sign_time, amount, with_tax_amount, tax_amount, materials, purchase_way_id, pay_way_id } = formState.value;

			const params = {
				id,
				parent_id: formState.value.parent_id,
				name,
				type,
				price_type,
				material_type,
				code,
				contact,
				file_path,
				project_id,
				plan_id,
				supplier_id,
				sign_time,
				amount,
				with_tax_amount,
				tax_amount,
				materials,
				purchase_way_id,
				pay_way_id
			};
			params.file_path = JSON.stringify(params.file_path);
			if (formState.value.art_indexes && formState.value.art_indexes.length) {
				params.art_indexes = JSON.stringify(formState.value.art_indexes.filter(d => d.gonghao_id && d.price));
			} else {
				params.art_indexes = JSON.stringify([]);
			}

			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}
			for (const material of params.materials) {
				// if (formState.value.price_type === 2 && !parseFloat(material.up_per) && !parseFloat(material.down_per)) {
				// 	proxy.$message.error("浮动价格合同必须输入浮动比率");
				// 	return;
				// }
				if (!material.with_tax_amount || !material.without_tax_amount) {
					proxy.$message.error("请完善合同材料清单信息");
					return;
				}
			}

			params.materials = JSON.stringify(
				params.materials.map(({ id, intro, unit, quantity, without_tax_subprice_base, down_per, up_per, without_tax_subprice, without_tax_amount, tax, with_tax_amount, with_tax_subprice, tax_amount, memo }) => {
					return {
						id,
						intro,
						unit,
						quantity,
						without_tax_subprice_base,
						down_per,
						up_per,
						without_tax_subprice,
						without_tax_amount,
						tax,
						tax_amount,
						with_tax_subprice,
						with_tax_amount,
						memo
					};
				})
			);
			loading.value = true
			postJson("contract/save", params)
				.then(data => {
					loading.value = false
					if (id) {
						proxy.$message.success("合同修改成功", 1);
					} else {
						proxy.$message.success("合同创建成功", 1);
						router.push(`/contract/${route.params.id}/child/edit/${data?.id}`);
					}
					/*
              closeTab("/contract");
              localStorage.removeItem("contract-save");
              */
				})
				.catch(err => {
					proxy.$message.error(err);
					loading.value = false
				});
		})
		.catch(err => {
			proxy.$message.error(err?.message);
		});
};
const submitPurchase = () => {
	proxy.$message.success("合同提交成功", 1);
	closeTab("/contract");
};

const closeTab = inject("closeTab");
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;

  .change-red{
	// background: red;
	:deep .ant-input-number{
		color: red;
		border: solid 1px red;
	}
	:deep .ant-select-selector{
		color: red;
		border: solid 1px red
	}
	input{
		color: red;
		border: solid 1px red
	}
  }

  h2 {
    font-size: 16px;
    font-weight: 600;
    line-height: 30px;
    margin-bottom: 20px;
  }

  h3 {
    line-height: 40px;
    font-size: 16px;
    font-weight: 400;
    margin-bottom: 20px;

    display: flex;
    align-items: center;

    &:before {
      content: "";
      display: block;
      width: 2px;
      height: 20px;
      background: rgb(24, 144, 255);
      margin-right: 10px;
    }
  }

  h4 {
    font-weight: 600;
    margin: 15px 0;
    line-height: 30px;
  }
}

:deep(.ant-table-cell) .ant-form-item {
  margin-bottom: 0;

  .ant-form-item-explain {
    position: absolute;
    bottom: -24px;
  }
}

.cache-btn {
  background-color: #0d9424;
  color: #fff;
}
</style>